use std::collections::HashMap;

use anyhow::Result;
use bollard::{
    network::{CreateNetworkOptions, ListNetworksOptions},
    Docker,
};

pub async fn create_network(docker: &Docker, network: String) -> Result<()> {
    let list = docker
        .list_networks(Some(ListNetworksOptions {
            filters: HashMap::from([("name", vec![network.as_str()])]),
        }))
        .await?;

    if list
        .iter()
        .any(|item| item.name.as_ref().is_some_and(|name| *name == network))
    {
        return Ok(());
    }

    let res = docker
        .create_network(CreateNetworkOptions {
            name: network,
            ..Default::default()
        })
        .await?;
    println!("create network {}", res.id);

    Ok(())
}
